package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.example.mapper.QuestionMapper;
import org.example.mapper.QuestionOptionMapper;
import org.example.mapper.QuestionnaireMapper;
import org.example.mapper.UserResponseMapper;
import org.example.model.Question;
import org.example.model.QuestionOption;
import org.example.model.Questionnaire;
import org.example.model.UserResponse;
import org.example.repository.QuestionnaireRepository;
import org.example.repository.UserResponseRepository;
import org.example.service.QuestionnaireService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class QuestionnaireServiceImpl implements QuestionnaireService {

    @Autowired
    private QuestionnaireRepository questionnaireRepository;

    @Autowired
    private UserResponseRepository userResponseRepository;
    
    // MyBatis-Plus Mapper
    @Autowired
    private QuestionnaireMapper questionnaireMapper;

    @Autowired
    private QuestionMapper questionMapper;
    
    @Autowired
    private QuestionOptionMapper questionOptionMapper;

    @Autowired
    private UserResponseMapper userResponseMapper;

    @Override
    @Transactional
    public Questionnaire createQuestionnaire(Questionnaire questionnaire) {
        // 设置创建时间和更新时间
        Date now = new Date();
        questionnaire.setCreateTime(now);
        questionnaire.setUpdateTime(now);
        questionnaire.setActive(true);
        
        // 设置默认创建者ID为1
        if (questionnaire.getCreatorId() == null) {
            questionnaire.setCreatorId(1L);
        }
        
        // 使用MyBatis-Plus保存问卷
        questionnaireMapper.insert(questionnaire);
        
        // 保存问题
        if (questionnaire.getQuestions() != null && !questionnaire.getQuestions().isEmpty()) {
            for (Question question : questionnaire.getQuestions()) {
                // 设置问卷ID
                question.setQuestionnaireId(questionnaire.getId());
                // 保存问题
                questionMapper.insert(question);
                
                // 保存选项
                if (question.getOptions() != null && !question.getOptions().isEmpty()) {
                    for (String optionText : question.getOptions()) {
                        QuestionOption option = new QuestionOption();
                        option.setQuestionId(question.getId());
                        option.setOptionText(optionText);
                        questionOptionMapper.insert(option);
                    }
                }
            }
        }
        
        return questionnaire;
    }

    @Override
    public List<Questionnaire> getAllQuestionnaires() {
        // 使用MyBatis-Plus获取所有活跃的问卷
        return questionnaireMapper.findByActiveTrue();
    }

    @Override
    public Questionnaire getQuestionnaireById(Long id) {
        // 使用MyBatis-Plus根据ID获取问卷
        Questionnaire questionnaire = questionnaireMapper.selectById(id);
        
        if (questionnaire != null) {
            // 查询问卷的所有问题
            List<Question> questions = questionMapper.findByQuestionnaireId(questionnaire.getId());
            
            // 为每个问题加载选项
            for (Question question : questions) {
                // 只有单选题和多选题需要加载选项
                if ("radio".equals(question.getType()) || "checkbox".equals(question.getType())) {
                    List<QuestionOption> options = questionOptionMapper.findByQuestionId(question.getId());
                    List<String> optionTexts = options.stream()
                            .map(QuestionOption::getOptionText)
                            .collect(Collectors.toList());
                    question.setOptions(optionTexts);
                }
            }
            
            questionnaire.setQuestions(questions);
        }
        
        return questionnaire;
    }

    @Override
    public UserResponse saveUserResponse(UserResponse userResponse) {
        // 设置提交时间
        userResponse.setSubmitTime(new Date());
        
        // 使用MyBatis-Plus保存用户回答
        userResponseMapper.insert(userResponse);
        return userResponse;
    }

    @Override
    public List<UserResponse> getUserResponses(Long userId) {
        // 使用MyBatis-Plus获取用户的所有回答
        LambdaQueryWrapper<UserResponse> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserResponse::getUserId, userId);
        return userResponseMapper.selectList(queryWrapper);
    }
    
    @Override
    @Transactional
    public void deleteQuestionnaire(Long id) {
        // 1. 先查询问卷是否存在
        Questionnaire questionnaire = questionnaireMapper.selectById(id);
        if (questionnaire == null) {
            throw new RuntimeException("问卷不存在");
        }
        
        // 2. 查询问卷下的所有问题
        List<Question> questions = questionMapper.findByQuestionnaireId(id);
        
        // 3. 删除每个问题的选项
        for (Question question : questions) {
            // 删除问题的选项
            LambdaQueryWrapper<QuestionOption> optionWrapper = new LambdaQueryWrapper<>();
            optionWrapper.eq(QuestionOption::getQuestionId, question.getId());
            questionOptionMapper.delete(optionWrapper);
            
            // 如果问题有图片，尝试删除图片文件
            if (question.getImageUrl() != null && !question.getImageUrl().isEmpty()) {
                try {
                    // 提取文件名
                    String fileName = question.getImageUrl();
                    if (fileName.startsWith("/image/question/")) {
                        fileName = fileName.substring("/image/question/".length());
                        File imageFile = new File("image/question/" + fileName);
                        if (imageFile.exists()) {
                            imageFile.delete();
                        }
                    }
                } catch (Exception e) {
                    // 图片删除失败不影响问卷删除
                    System.out.println("删除问题图片失败: " + e.getMessage());
                }
            }
        }
        
        // 4. 删除问卷的所有问题
        LambdaQueryWrapper<Question> questionWrapper = new LambdaQueryWrapper<>();
        questionWrapper.eq(Question::getQuestionnaireId, id);
        questionMapper.delete(questionWrapper);
        
        // 5. 删除问卷
        questionnaireMapper.deleteById(id);
    }
    
    @Override
    @Transactional
    public Questionnaire updateQuestionnaire(Questionnaire questionnaire) {
        // 1. 验证问卷是否存在
        Questionnaire existingQuestionnaire = questionnaireMapper.selectById(questionnaire.getId());
        if (existingQuestionnaire == null) {
            throw new RuntimeException("问卷不存在");
        }
        
        // 2. 更新问卷基本信息
        existingQuestionnaire.setTitle(questionnaire.getTitle());
        existingQuestionnaire.setDescription(questionnaire.getDescription());
        existingQuestionnaire.setUpdateTime(new Date());
        questionnaireMapper.updateById(existingQuestionnaire);
        
        // 3. 获取现有问题列表
        List<Question> existingQuestions = questionMapper.findByQuestionnaireId(questionnaire.getId());
        Map<Long, Question> existingQuestionMap = existingQuestions.stream()
                .collect(Collectors.toMap(Question::getId, q -> q));
        
        // 4. 处理问题更新
        for (Question question : questionnaire.getQuestions()) {
            if (question.getId() != null) {
                // 4.1 更新现有问题
                Question existingQuestion = existingQuestionMap.get(question.getId());
                if (existingQuestion != null) {
                    // 更新问题内容
                    existingQuestion.setContent(question.getContent());
                    existingQuestion.setType(question.getType());
                    existingQuestion.setImageUrl(question.getImageUrl());
                    questionMapper.updateById(existingQuestion);
                    
                    // 移除已处理的问题，剩下的将被删除
                    existingQuestionMap.remove(question.getId());
                    
                    // 更新选项
                    // 先删除现有选项
                    LambdaQueryWrapper<QuestionOption> optionWrapper = new LambdaQueryWrapper<>();
                    optionWrapper.eq(QuestionOption::getQuestionId, question.getId());
                    questionOptionMapper.delete(optionWrapper);
                    
                    // 添加新选项
                    if (question.getOptions() != null && !question.getOptions().isEmpty()) {
                        for (String optionText : question.getOptions()) {
                            QuestionOption option = new QuestionOption();
                            option.setQuestionId(question.getId());
                            option.setOptionText(optionText);
                            questionOptionMapper.insert(option);
                        }
                    }
                }
            } else {
                // 4.2 添加新问题
                question.setQuestionnaireId(questionnaire.getId());
                questionMapper.insert(question);
                
                // 添加选项
                if (question.getOptions() != null && !question.getOptions().isEmpty()) {
                    for (String optionText : question.getOptions()) {
                        QuestionOption option = new QuestionOption();
                        option.setQuestionId(question.getId());
                        option.setOptionText(optionText);
                        questionOptionMapper.insert(option);
                    }
                }
            }
        }
        
        // 5. 删除不再需要的问题
        for (Question questionToDelete : existingQuestionMap.values()) {
            // 删除问题的选项
            LambdaQueryWrapper<QuestionOption> optionWrapper = new LambdaQueryWrapper<>();
            optionWrapper.eq(QuestionOption::getQuestionId, questionToDelete.getId());
            questionOptionMapper.delete(optionWrapper);
            
            // 如果问题有图片，尝试删除图片文件
            if (questionToDelete.getImageUrl() != null && !questionToDelete.getImageUrl().isEmpty()) {
                try {
                    // 提取文件名
                    String fileName = questionToDelete.getImageUrl();
                    if (fileName.startsWith("/image/question/")) {
                        fileName = fileName.substring("/image/question/".length());
                        File imageFile = new File("image/question/" + fileName);
                        if (imageFile.exists()) {
                            imageFile.delete();
                        }
                    }
                } catch (Exception e) {
                    // 图片删除失败不影响问卷更新
                    System.out.println("删除问题图片失败: " + e.getMessage());
                }
            }
            
            // 删除问题
            questionMapper.deleteById(questionToDelete.getId());
        }
        
        // 6. 返回更新后的问卷（重新查询以获取完整数据）
        return getQuestionnaireById(questionnaire.getId());
    }
} 